package com.wangzhixuan.apiController;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wangzhixuan.commons.base.ApiBaseController;
import com.wangzhixuan.commons.constant.ApiCode;
import com.wangzhixuan.commons.scan.MyException;
import com.wangzhixuan.commons.utils.StringUtils;
import com.wangzhixuan.model.History;
import com.wangzhixuan.model.Skydrive;
import com.wangzhixuan.service.IHistoryService;
import com.wangzhixuan.service.ISkydriveService;

/**
 * <p>
 *   前端控制器
 * </p>
 * @author zhixuan.wang
 * @since 2017-08-22
 */
@Controller
@RequestMapping("/api")
public class SkydriveApiController extends ApiBaseController {
    
    @Autowired private ISkydriveService skydriveService;
    
    @Autowired private IHistoryService historyService;

    @RequestMapping("/folder/add")
    @ResponseBody
    public Object folderAdd(Integer userId,Integer fileId,String folderName) throws IllegalAccessException, InvocationTargetException, MyException {
    	if (userId == null  ) {
			throw new MyException(ApiCode.CODE_501, "请重新登录");
		}
		if (fileId == null) {
			throw new MyException(ApiCode.CODE_501, "网络异常，请稍后重试");
		}
		if (StringUtils.isBlank(folderName)) {
			throw new MyException(ApiCode.CODE_501, "网络异常，请稍后重试");
		}
    	Skydrive pSkydrive = skydriveService.selectById(fileId);
    	if(pSkydrive==null){
    		throw new MyException(ApiCode.CODE_500, "父文件夹不存在，不能创建文件夹");
    	}
    	Skydrive skydrive = new Skydrive();
    	skydrive.setPid(fileId);
    	skydrive.setCreateId(userId);
    	skydrive.setFileName(folderName);
    	skydrive.setFileFullName(pSkydrive.getFileFullName()+">>>"+folderName);
    	skydrive.setIsForder(1);
    	skydrive.setIsShare(pSkydrive.getIsShare());
    	skydrive.setCreateTime(new Date());
    	skydrive.setModifyTime(new Date());
        boolean b = skydriveService.insert(skydrive);
        if (b) {
        	return renderSuccess(ApiCode.CODE_200, "成功");
        } else {
        	return renderError(ApiCode.CODE_500, "创建失败");
        }
    }
    
    /**
     * 获取当前文件列表
     * @param userId
     * @param fileId
     * @return
     * @throws MyException
     */
    @RequestMapping("/file/detailed")
    @ResponseBody
    public Object detailed(Integer userId,Integer fileId) throws MyException{
    	if (userId == null  ) {
			throw new MyException(ApiCode.CODE_501, "请重新登录");
		}
		if (fileId == null) {
			throw new MyException(ApiCode.CODE_501, "网络异常，请稍后重试");
		}
		List<Map<String,Object>> fileDetailed = skydriveService.selectFileDetailed(userId, fileId);
		return renderSuccess(ApiCode.CODE_200, "成功",fileDetailed==null?"":fileDetailed);
    }
    
    /**
     * 获取共享文件列表
     * @param userId
     * @param fileId
     * @return
     * @throws MyException
     */
    @RequestMapping("/file/GXdetailed")
    @ResponseBody
    public Object GXdetailed(Integer userId,Integer fileId) throws MyException{
    	if (userId == null  ) {
			throw new MyException(ApiCode.CODE_501, "请重新登录");
		}
		if (fileId == null) {
			throw new MyException(ApiCode.CODE_501, "网络异常，请稍后重试");
		}
		List<Map<String,Object>> fileDetailed = skydriveService.selectGXFileDetailed(userId, fileId);
		return renderSuccess(ApiCode.CODE_200, "成功",fileDetailed==null?"":fileDetailed);
    }
    
    /**
     * 获取历史记录
     * @param userId
     * @return
     * @throws MyException
     */
    @RequestMapping("/file/lately")
    @ResponseBody
    public Object lately(Integer userId) throws MyException{
    	if (userId == null) {
			throw new MyException(ApiCode.CODE_501, "请重新登录");
		}
    	List<Map<String,Object>> history = skydriveService.selectHistory(userId);
    	return renderSuccess(ApiCode.CODE_200, "成功",history==null?"":history);
    }
    
    /**
     * 添加历史记录
     * @param userId
     * @param fileId
     * @return
     * @throws MyException
     */
    @RequestMapping("/file/open")
    @ResponseBody
    public Object fileOpen(Integer userId,Integer fileId) throws MyException{
    	if (userId == null  ) {
			throw new MyException(ApiCode.CODE_501, "请重新登录");
		}
    	if (fileId == null  ) {
			throw new MyException(ApiCode.CODE_501, "网络异常，请稍后重试");
		}
    	Skydrive skydrive = skydriveService.selectById(fileId);
    	if(skydrive==null){
    		return renderError(ApiCode.CODE_500, "文件不存在");
    	}
    	String fileUrl = skydrive.getFileUrl();
    	String fileName = skydrive.getFileName();
    	HashMap<String,Object> resultmap = new HashMap<String,Object>();
    	resultmap.put("openFileLink", fileUrl==null?"":fileUrl);
    	resultmap.put("fileName", fileName==null?"":fileName);
    	Integer id = historyService.selectHistoryFid(fileId);
    	if(id != null){
    		History history = historyService.selectById(id);
    		history.setVisitTime(new Date());
    		historyService.updateById(history);
    		return renderSuccess(ApiCode.CODE_200, "成功",resultmap);
    	}else {
        	History history = new History();
        	history.setSkyFileId(fileId);
        	history.setVisitId(userId);
        	history.setVisitTime(new Date());
        	boolean b = historyService.insert(history);
        	if(b){
        		return renderSuccess(ApiCode.CODE_200, "成功",resultmap);
        	}else{
        		return renderError(ApiCode.CODE_500, "添加历史纪录失败");
        	}
    	}
    }
    
    /**
     * 获取文件动态
     * @param userId
     * @return
     * @throws MyException
     */
	@RequestMapping("/folder/dynamic")
    @ResponseBody
    public Object dynamic(Integer userId) throws MyException{
    	if (userId == null  ) {
			throw new MyException(ApiCode.CODE_501, "请重新登录");
		}
    	Map<String, Object> map = skydriveService.selectDynamic(userId);
    	if(map==null){
    		Map<String, Object> mapNull = new HashMap<String, Object>();
    		mapNull.put("uploadNum", "");
    		mapNull.put("uploadTime", "");
    		mapNull.put("uploadName", "");
    		return renderSuccess(ApiCode.CODE_200, "成功",mapNull);
    	}
		return renderSuccess(ApiCode.CODE_200, "成功",map);
    }
    
    @RequestMapping("folder/dynamicHistory")
    @ResponseBody
    public Object dynamicHistory(Integer userId) throws MyException{
    	if (userId == null  ) {
			throw new MyException(ApiCode.CODE_501, "请重新登录");
		}
    	List<Map<String, Object>> dynamicHistory = skydriveService.dynamicHistory(userId);
		return renderSuccess(ApiCode.CODE_200, "成功",dynamicHistory);
    }
    
    
    /**
     * 删除
     * @param id
     * @return
     * @throws MyException 
     */
    @RequestMapping("/file/delete")
    @ResponseBody
    public Object delete(Integer fileId,HttpServletRequest request) throws MyException {
    	if(fileId==304||fileId==305){
    		throw new MyException(ApiCode.CODE_506, "无法删除");
    	}else{
    		Skydrive skydrive = skydriveService.selectById(fileId);
    		if(skydrive.getIsForder()==1){
            	List<Skydrive> son = skydriveService.selectSon(fileId);
        		if(son.size()!= 0){
        			throw new MyException(ApiCode.CODE_506, "请先删除文件夹下的文件");
        		}
    		}
    		if(skydrive.getIsForder() == 0){			//如果是文件要删除本地文件
        		String fileUrl = skydrive.getFileUrl();
        		System.out.println(getbaseUrl(request));
        		String replace = fileUrl.replace(getbaseUrl(request),"");
        		String newfileUrl = getRootPath()+replace;
        		System.out.println(newfileUrl);
        		File file = new File(newfileUrl);
        		file.delete();
    		}
            boolean b = skydriveService.deleteById(fileId);
            if (b) {
            	return renderSuccess(ApiCode.CODE_200, "删除成功");
            } else {
                return renderError(ApiCode.CODE_200,"删除失败！");
            }
    	}
    }
    
    
    /**
     * 删除
     * @param id
     * @return
     * @throws MyException 
     */
    @RequestMapping("/file/answer")
    @ResponseBody
    public Object answer(Integer fileId) throws MyException {
    	if(fileId==null){
    		throw new MyException(ApiCode.CODE_501, "请选择文件");
    	}    		
    	List<Skydrive> son = skydriveService.selectSon(fileId);
		if(son != null){
			return renderSuccess(ApiCode.CODE_200, "文件夹不为空");
		}
		return renderSuccess(ApiCode.CODE_200, "空文件夹");
    }
}
